#!/bin/bash
# 当前目录  如果是当前目录，可以不填
HOME_DIR=
# jar名   如果当前目录只有一个jar，可以不填
APP_NAME=
# 启动环境
ACTIVE=
# 启动端口
PORT=
# 远程调试端口 如果不进行远程调试，这一项不填
DEBUG_PORT=
# 远程调试命令
DEBUG_SH="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$DEBUG_PORT"
# 最大堆内存
XMX=
# 初始化堆内存
XMS=
# 其他jvm参数
JVM_PARAMS=
# 输出文件
OUT_FILE=
# 启动脚本
START_SH=

# 生成启动脚本
gen_start_sh() {
    # 判断当前目录
    if [ "$HOME_DIR" = "" ];then
        HOME_DIR=$(cd $(dirname $0); pwd)
    fi

    # 判断jar名
    if [ "$APP_NAME" = "" ];then
        APP_NAME=$(ls *.jar)
    fi

    # 生成启动命令
    START_SH="nohup java -jar"

    # 添加最大内存
    if [ "$XMX" != "" ];then
        START_SH="$START_SH"" -Xmx=$(XMX)"
    fi

    # 添加初始化堆内存
    if [ "$XMS" != "" ];then
        START_SH="$START_SH"" -Xms=$(XMS)"
    fi

    # 判断是否调试
    if [ "$DEBUG_PORT" != "" ];then
        START_SH="$START_SH"" $DEBUG_SH"
    fi

    # 添加其他jvm参数
    if [ "$JVM_PARAMS" != "" ];then
        START_SH="$START_SH"" $JVM_PARAMS"
    fi

    # 添加目录
    START_SH="$START_SH"" $HOME_DIR/$APP_NAME"

    # 判断启动环境
    if [ "$ACTIVE" != "" ];then
        START_SH="$START_SH"" --spring.profiles.active=$ACTIVE"
    fi

    # 判断启动端口
    if [ "$PORT" != "" ];then
        START_SH="$START_SH"" --server.port=$PORT"
    fi

    # 输出文件
    if [ "$OUT_FILE" != "" ];then
        START_SH="$START_SH"" >> $OUT_FILE 2>&1 &"
    else
        OUT_FILE=out.out
        START_SH="$START_SH"" >> out.out 2>&1 &"
    fi
}

# 检查程序是否存活   1: 存在  0: 不存在
is_run() {
    gen_start_sh
    pid=$(ps -aux | grep -v grep | grep $HOME_DIR/$APP_NAME | awk '{print $2}')
    if [ "$pid" = "" ];then
        return 0
    else
        return 1
    fi
}

# 启动程序
start() {
    # 生成启动脚本
    gen_start_sh
    # 判断程序是否在运行
    is_run
    if [ "$?" = "1" ];then
        echo "进程已经存在，请勿多次启动"
        exit 1
    fi
    # 启动程序
    eval $START_SH
    sleep 2
    is_run
    if [ "$?" = "1" ];then
        echo "进程已启动，请观察输出文件$OUT_FILE"
        tail -f $OUT_FILE
    else
        echo "进程启动失败，请检查"
    fi
}

#while [ 1 ]
#do
#    start=$(cat out.out | grep Start)
#    if [ "$start" = "" ];then
#        break
#    fi
#    sleep 1
#done

# 停止程序
stop() {
    # 生成启动脚本
    gen_start_sh
    # 判断程序是否在运行
    is_run
    if [ "$?" = "0" ];then
        echo "程序未运行"
        return
    fi
    # 获取进程pid
    pid=$(ps -aux | grep -v grep | grep $HOME_DIR/$APP_NAME | awk '{print $2}')
    # 杀死程序
    eval kill -9 $pid
    sleep 1
    is_run
    if [ "$?" = "0" ];then
        echo "程序已停止"
    else
        echo "进程停止失败，请检查"
    fi
}

restart() {
    echo "停止程序中..."
    stop
    sleep 1
    echo "启动程序中"
    start
}

test() {
    gen_start_sh
    echo "$START_SH"
}

if [ $# -eq 1 ] && [ $1 == "stop" ]; then
        stop
elif [ $# -eq 1 ] && [ $1 == "start" ]; then
        start
elif [ $# -eq 1 ] && [ $1 == "restart" ]; then
        restart
elif [ $# -eq 1 ] && [ $1 == "test" ]; then
    test
else
        echo "当前脚本只支持stop, start, restart, test命令"
fi